<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="35%"
    top="13vh"
    :before-close="closeHandle"
    :close-on-click-modal="false">
    <el-form :model="roleForm" :rules="roleRules" ref="roleForm" label-width="85px"
             @keyup.enter.native="enterFromHandle">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleForm.roleName" maxlength="50" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="21">
          <el-form-item label="角色简称" prop="roleKey">
            <el-input v-model="roleForm.roleKey" maxlength="30" placeholder="请输入角色简称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-tooltip placement="bottom" effect="light" class="warning-icon">
            <div slot="content">
              角色简称由大小写字母和下划线组成
            </div>
            <i class="el-icon-warning"></i>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-form-item label="排序等级" prop="sort">
        <el-input v-model.number="roleForm.sort" maxlength="5" placeholder="排序等级"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="roleForm.remark" maxlength="100" placeholder="备注"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeHandle(false)">取消</el-button>
      <el-button v-show="!optType" :disabled="buttonLoad" type="primary" @click="saveRoleHandle">添加</el-button>
      <el-button v-show="optType" :disabled="buttonLoad" type="primary"  @click="updateRoleHandle">修改</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    name: "role-save-update-dialog",
    data() {
      let checkRoleKey = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('角色键不能为空'))
        }
        // 正则表达式（必须由大小写字母和下划线组成）
        let regex = /^[a-zA-Z_]+$/g
        if (!regex.test(value)) {
          return callback(new Error('角色键不符合规则'))
        }
        callback()
      }
      return {
        // 弹出框显示状态[true-显示 false-隐藏]
        visible: false,
        // 角色表单对象
        roleForm: {
          // 角色id
          roleId: '',
          // 角色名字
          roleName: '',
          // 角色键
          roleKey: '',
          // 角色排序等级
          sort: '',
          // 角色描述
          remark: ''
        },
        // 弹出框标题
        dialogTitle: undefined,
        // 菜单添加或修改[false-添加 true-修改]
        optType: false,
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 角色表单校验规则
        roleRules: {
          roleName: [
            { required: true, message: '角色名称不能为空', trigger: 'blur' }
          ],
          roleKey: [
            { required: true, validator: checkRoleKey, trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '排序等级不能为空', trigger: 'blur' },
            { type: 'number', message: '排序等级必须为数字值'}
          ],
        }
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
    },
    methods: {
      /**
       * 初始化菜单弹出框事件
       * @param {Object}  role      角色对象
       * @param {Boolean} optType   操作类型[true-修改 false-添加]
       */
      initRoleDialog(role, optType) {
        // 打开弹出框
        this.visible = true;
        this.optType = optType
        this.dialogTitle = optType ? '角色修改' : '添加角色'

        let roleForm = this.roleForm;
        if (optType) {
          this.$nextTick(() => {
            roleForm.roleId = role.roleId;
            roleForm.roleName = role.roleName;
            roleForm.roleKey = role.roleKey;
            roleForm.sort = role.sort;
            roleForm.remark = role.remark;
          });
        } else {

          this.getNextSort();
        }
      },
      /**
       * 获取角色下一个默认排序等级方法
       */
      getNextSort() {
        this.$axios.$get('/sys/role/next/sort')
          .then(({ data }) => {
            this.roleForm.sort = data
          })
          .catch(() => {})
      },
      // 表单回车事件
      enterFromHandle() {
        if (this.optType) {
          this.updateRoleHandle()
        } else {
          this.saveRoleHandle()
        }
      },
      // 添加菜单事件
      saveRoleHandle() {
        this.$refs.roleForm.validate((valid) => {
          if (!valid) {
            return
          }
          // 按钮不可被点击
          this.buttonLoad = true

          let roleForm = this.roleForm;
          this.$axios.$post('/sys/role/save', roleForm)
            .then(() => {
              this.notify('success', '添加成功', `成功添加'${roleForm.roleName}'角色`)

              // 关闭弹出框
              this.closeHandle(true)
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.buttonLoad = false
            })
        })
      },
      // 修改角色事件
      updateRoleHandle() {
        this.$refs.roleForm.validate((valid) => {
          if (!valid) {
            return
          }
          // 按钮不可被点击
          this.buttonLoad = true

          // 修改系统角色表单对象
          let roleForm = this.roleForm
          this.$axios.$post('/sys/role/update', roleForm)
            .then(() => {

              this.notify('success', '操作成功', `'${roleForm.roleName}'角色修改成功`)

              // 角色操作弹出框关闭
              this.closeHandle(true)
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.buttonLoad = false
            })
        })
      },
      // 弹出框关闭处理事件
      closeHandle(bool) {
        // 角色表单重置
        this.$refs.roleForm.resetFields()
        // 手动清空角色主键
        this.roleForm.roleId = ''

        if (typeof bool === 'function') {
          // 此处判断触发事件是否是弹出框自带关闭事件
          bool = false
        }
        // 向上传递事件
        this.$emit('close-dialog', bool)
        this.$nextTick(() => {
          // 关闭弹出框
          this.visible = false;
        });
      },
    }
  }
</script>


<!--
  css字符对应
  r -> role
-->
<style>
  .tree-border {
    margin-top: 5px;
    border: 1px solid #e5e6e7;
    background: #fff none;
    border-radius: 4px;
  }
</style>

<style scoped>
  .role-from {
    position: relative;
    box-sizing: border-box;
  }
  .role-from:before, .role-from:after {
    display: table;
    content: "";
  }
  .role-from:after {
    clear: both;
  }
  .role-from .r-sort, .role-from .r-status {
    width: 50%;
    float: left;
    box-sizing: border-box;
  }
  .r-sort .number-input {
    width: 100%;
  }
  .warning-icon {
    line-height: 32px;
    font-size: 20px;
    text-align: center;
    color: #e6a23c;
    cursor: pointer;
  }
</style>
